<?php 

namespace pmvc\util;

use Exception;
use DOMElement;
use SimpleXMLElement;

/**
 * Utilities for working with xml.
 * 
 */
class XMLUtil {

	/**
	 * Returns the given attribute from the given element
	 * or the default value if it's not found
	 * 
	 * @param mixed $element
	 * @param string $name
	 * @param mixed $default
	 */
	public static function getAttributeValue($element, $name, $default=null) {
		if ($element instanceof DOMElement) {
			return ($element->hasAttribute($name)) ? $element->getAttribute($name) : $default;
		} else if ($element instanceof SimpleXMLElement) {
			$val = (string)$element[$name];
			return  (!empty($val)) ? $val: $default;
		}
		throw new Exception("Unknown element type: ".get_class($element));
	}

	/**
	 * Returns the attribute value of the given element or
	 * the sub element if it exists.
	 * 
	 * @param mixed $element
	 * @param string $name
	 * @param mixed $default
	 * @param string $subElementName
	 * @return string
	 */
	public static function getAttributeValueOrSubElementText($element, $name=null, $default=null, $subElementName=null) {
		$subElementName = isset($subElementName) ? $subElementName : $name;

		// try attribute
		$value = self::getAttributeValue($element, $name, null);
		if (isset($value)) {
			return $value;
		}

		// try sub element
		if ($element instanceof DOMElement) {
			$child = self::findChildElement($element, $subElementName);
			return $child!=null ? $child->textContent : $default;
		} else if ($element instanceof SimpleXMLElement) {
			return isset($element->$subElementName) ? (string)$element->$subElementName : $default;
		}
	}

	/**
	 * Checks to see if the given element has a child of the given name..
	 * @param mixed $element
	 * @param string $name
	 * @return bool
	 * @throws Exception
	 */
	public static function hasChildElement($element, $name) {
		return self::findChildElement($element, $name)!=null;
	}

	/**
	 * Finds a child element.
	 * @param mixed $element
	 * @param string $name
	 * @return mixed
	 * @throws Exception on error
	 */
	public static function findChildElement($element, $name) {
		if ($element instanceof DOMElement) {
			for ($i=0; $i<$element->childNodes->length; $i++) {
				$node = $element->childNodes->item($i);
				if ($node instanceof DOMElement
					&& $node->tagName==$name) {
					return $node;
				}
			}
			return null;
		} else if ($element instanceof SimpleXMLElement) {
			return $element->$subElementName;
		}
		throw new Exception("Unknown element type: ".get_class($element));
	}
	
}

?>